<template>
  <view class="container">

    <!-- 工具分类 -->
    <view class="tools-container">
      <!-- 常用工具 -->
      <view class="tool-section">
        <text class="section-title">常用工具</text>
        <view class="tool-grid">
          <view 
            class="tool-item" 
            v-for="tool in filteredCommonTools" 
            :key="tool.id"
            @click="openTool(tool)"
          >
            <view class="tool-icon-wrapper" :style="{ backgroundColor: tool.bgColor }">
              <image :src="tool.icon" class="tool-icon" />
            </view>
            <text class="tool-label">{{ tool.label }}</text>
          </view>
        </view>
      </view>

      <!-- 计算工具 -->
      <view class="tool-section">
        <text class="section-title">计算工具</text>
        <view class="tool-grid">
          <view 
            class="tool-item" 
            v-for="tool in filteredCalcTools" 
            :key="tool.id"
            @click="openTool(tool)"
          >
            <view class="tool-icon-wrapper" :style="{ backgroundColor: tool.bgColor }">
              <image :src="tool.icon" class="tool-icon" />
            </view>
            <text class="tool-label">{{ tool.label }}</text>
          </view>
        </view>
      </view>

      <!-- 转换工具 -->
      <view class="tool-section">
        <text class="section-title">转换工具</text>
        <view class="tool-grid">
          <view 
            class="tool-item" 
            v-for="tool in filteredConvertTools" 
            :key="tool.id"
            @click="openTool(tool)"
          >
            <view class="tool-icon-wrapper" :style="{ backgroundColor: tool.bgColor }">
              <image :src="tool.icon" class="tool-icon" />
            </view>
            <text class="tool-label">{{ tool.label }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 计算器弹窗 -->
    <view class="modal" v-if="showCalculator" @click="closeCalculator">
      <view class="modal-content calculator-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">计算器</text>
          <view class="close-btn" @click="closeCalculator">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="calculator-display">
          <text class="calculator-expression">{{ calculatorExpression }}</text>
          <text class="calculator-result">{{ calculatorResult }}</text>
        </view>
        <view class="calculator-buttons">
          <view class="button-row" v-for="(row, rowIndex) in calculatorButtons" :key="rowIndex">
            <view 
              class="calc-btn" 
              :class="btn.class"
              v-for="btn in row" 
              :key="btn.value"
              @click="calculatorClick(btn.value)"
            >
              <text class="calc-btn-text">{{ btn.label }}</text>
            </view>
          </view>
        </view>
      </view>
    </view>

    <!-- 单位转换弹窗 -->
    <view class="modal" v-if="showConverter" @click="closeConverter">
      <view class="modal-content converter-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">{{ currentConverter.title }}</text>
          <view class="close-btn" @click="closeConverter">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="converter-content">
          <view class="converter-input-group">
            <input 
              class="converter-input" 
              v-model="converterInput" 
              type="number"
              placeholder="输入数值"
            />
            <picker 
              class="converter-picker" 
              :range="currentConverter.units" 
              @change="onFromUnitChange"
            >
              <text class="picker-text">{{ fromUnit }}</text>
            </picker>
          </view>
          <view class="converter-arrow">
            <image src="/static/arrow-right.png" class="arrow-icon" />
          </view>
          <view class="converter-input-group">
            <input 
              class="converter-input" 
              v-model="converterOutput" 
              disabled
            />
            <picker 
              class="converter-picker" 
              :range="currentConverter.units" 
              @change="onToUnitChange"
            >
              <text class="picker-text">{{ toUnit }}</text>
            </picker>
          </view>
        </view>
      </view>
    </view>

    <!-- 备忘录弹窗 -->
    <view class="modal" v-if="showMemo" @click="closeMemo">
      <view class="modal-content memo-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">备忘录</text>
          <view class="memo-actions">
            <text class="save-btn" @click="saveMemo">保存</text>
            <view class="close-btn" @click="closeMemo">
              <text class="close-icon">×</text>
            </view>
          </view>
        </view>
        <view class="memo-content">
          <textarea 
            class="memo-textarea" 
            v-model="memoContent" 
            placeholder="记录重要信息..."
            maxlength="1000"
          />
          <text class="memo-count">{{ memoContent.length }}/1000</text>
        </view>
        <view class="memo-list" v-if="memoList.length > 0">
          <text class="memo-list-title">历史记录</text>
          <view 
            class="memo-item" 
            v-for="(memo, index) in memoList" 
            :key="index"
            @click="loadMemo(index)"
          >
            <text class="memo-item-content">{{ memo.content.substring(0, 50) }}{{ memo.content.length > 50 ? '...' : '' }}</text>
            <text class="memo-item-time">{{ memo.time }}</text>
          </view>
        </view>
      </view>
    </view>

    <!-- 二维码生成弹窗 -->
    <view class="modal" v-if="showQRCode" @click="closeQRCode">
      <view class="modal-content qrcode-modal" @click.stop>
        <view class="modal-header">
          <text class="modal-title">二维码生成</text>
          <view class="close-btn" @click="closeQRCode">
            <text class="close-icon">×</text>
          </view>
        </view>
        <view class="qrcode-content">
          <input 
            class="qrcode-input" 
            v-model="qrcodeText" 
            placeholder="输入要生成二维码的内容"
          />
          <button class="generate-btn" @click="generateQRCode">生成二维码</button>
          <view class="qrcode-display" v-if="qrcodeImage">
            <image :src="qrcodeImage" class="qrcode-image" />
            <button class="save-qrcode-btn" @click="saveQRCode">保存图片</button>
          </view>
        </view>
      </view>
    </view>
  </view>
</template>

<script setup>
import { ref, computed, onMounted } from 'vue'

// 响应式数据
const showSearchBar = ref(false)
const searchKeyword = ref('')
const showCalculator = ref(false)
const showConverter = ref(false)
const showMemo = ref(false)
const showQRCode = ref(false)

// 计算器相关
const calculatorExpression = ref('')
const calculatorResult = ref('0')

// 单位转换相关
const currentConverter = ref({})
const converterInput = ref('')
const converterOutput = ref('')
const fromUnit = ref('')
const toUnit = ref('')

// 备忘录相关
const memoContent = ref('')
const memoList = ref([
  { content: '检查A栋空调系统运行状态', time: '2024-01-15 09:30' },
  { content: '维修B栋电梯故障，需要更换零件', time: '2024-01-14 14:20' }
])

// 二维码相关
const qrcodeText = ref('')
const qrcodeImage = ref('')

// 工具数据
const commonTools = [
  { id: 'calculator', label: '计算器', icon: '/static/计算器.png', bgColor: '#3D76FF', type: 'calculator' },
  { id: 'memo', label: '备忘录', icon: '/static/备忘录.png', bgColor: '#FF6B35', type: 'memo' },
  { id: 'flashlight', label: '手电筒', icon: '/static/手电筒.png', bgColor: '#FFC107', type: 'flashlight' }
]

const calcTools = [
  { id: 'area', label: '面积计算', icon: '/static/面积计算.png', bgColor: '#9C27B0', type: 'area' },
  { id: 'volume', label: '体积计算', icon: '/static/体积计算.png', bgColor: '#E91E63', type: 'volume' },
  { id: 'power', label: '功率计算', icon: '/static/功率计算.png', bgColor: '#607D8B', type: 'power' }
]

const convertTools = [
  { id: 'length', label: '长度转换', icon: '/static/长度转换.png', bgColor: '#2196F3', type: 'length' },
  { id: 'area_convert', label: '面积转换', icon: '/static/面积转换.png', bgColor: '#4CAF50', type: 'area_convert' },
  { id: 'temperature', label: '温度转换', icon: '/static/温度转换.png', bgColor: '#FF5722', type: 'temperature' }
]

// 计算器按钮
const calculatorButtons = [
  [
    { label: 'C', value: 'clear', class: 'btn-clear' },
    { label: '±', value: 'toggle', class: 'btn-operator' },
    { label: '%', value: '%', class: 'btn-operator' },
    { label: '÷', value: '/', class: 'btn-operator' }
  ],
  [
    { label: '7', value: '7', class: 'btn-number' },
    { label: '8', value: '8', class: 'btn-number' },
    { label: '9', value: '9', class: 'btn-number' },
    { label: '×', value: '*', class: 'btn-operator' }
  ],
  [
    { label: '4', value: '4', class: 'btn-number' },
    { label: '5', value: '5', class: 'btn-number' },
    { label: '6', value: '6', class: 'btn-number' },
    { label: '-', value: '-', class: 'btn-operator' }
  ],
  [
    { label: '1', value: '1', class: 'btn-number' },
    { label: '2', value: '2', class: 'btn-number' },
    { label: '3', value: '3', class: 'btn-number' },
    { label: '+', value: '+', class: 'btn-operator' }
  ],
  [
    { label: '0', value: '0', class: 'btn-number btn-zero' },
    { label: '.', value: '.', class: 'btn-number' },
    { label: '=', value: '=', class: 'btn-equal' }
  ]
]

// 单位转换器配置
const converterConfigs = {
  length: {
    title: '长度转换',
    units: ['米', '厘米', '毫米', '千米', '英寸', '英尺', '码'],
    conversions: {
      '米': 1,
      '厘米': 0.01,
      '毫米': 0.001,
      '千米': 1000,
      '英寸': 0.0254,
      '英尺': 0.3048,
      '码': 0.9144
    }
  },
  area_convert: {
    title: '面积转换',
    units: ['平方米', '平方厘米', '平方毫米', '公顷', '亩', '平方英尺'],
    conversions: {
      '平方米': 1,
      '平方厘米': 0.0001,
      '平方毫米': 0.000001,
      '公顷': 10000,
      '亩': 666.67,
      '平方英尺': 0.0929
    }
  },
  temperature: {
    title: '温度转换',
    units: ['摄氏度', '华氏度', '开尔文'],
    conversions: {
      '摄氏度': 'celsius',
      '华氏度': 'fahrenheit',
      '开尔文': 'kelvin'
    }
  }
}

// 计算属性
const filteredCommonTools = computed(() => {
  if (!searchKeyword.value) return commonTools
  return commonTools.filter(tool => 
    tool.label.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const filteredCalcTools = computed(() => {
  if (!searchKeyword.value) return calcTools
  return calcTools.filter(tool => 
    tool.label.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

const filteredConvertTools = computed(() => {
  if (!searchKeyword.value) return convertTools
  return convertTools.filter(tool => 
    tool.label.toLowerCase().includes(searchKeyword.value.toLowerCase())
  )
})

// 方法
const goBack = () => {
  uni.navigateBack()
}

const showSearch = () => {
  showSearchBar.value = true
}

const hideSearch = () => {
  showSearchBar.value = false
  searchKeyword.value = ''
}

const filterTools = () => {
  // 搜索功能已通过计算属性实现
}

const openTool = (tool) => {
  switch (tool.type) {
    case 'calculator':
      showCalculator.value = true
      break
    case 'memo':
      showMemo.value = true
      break
    case 'qrcode':
      showQRCode.value = true
      break
    case 'flashlight':
      toggleFlashlight()
      break
    case 'length':
    case 'area_convert':
    case 'temperature':
      openConverter(tool.type)
      break
    default:
      uni.showToast({ title: '功能开发中', icon: 'none' })
  }
}

// 计算器功能
const calculatorClick = (value) => {
  switch (value) {
    case 'clear':
      calculatorExpression.value = ''
      calculatorResult.value = '0'
      break
    case '=':
      try {
        const result = eval(calculatorExpression.value)
        calculatorResult.value = result.toString()
        calculatorExpression.value = result.toString()
      } catch (error) {
        calculatorResult.value = '错误'
      }
      break
    case 'toggle':
      if (calculatorExpression.value) {
        calculatorExpression.value = calculatorExpression.value.startsWith('-') 
          ? calculatorExpression.value.substring(1) 
          : '-' + calculatorExpression.value
      }
      break
    default:
      calculatorExpression.value += value
  }
}

const closeCalculator = () => {
  showCalculator.value = false
  calculatorExpression.value = ''
  calculatorResult.value = '0'
}

// 单位转换功能
const openConverter = (type) => {
  currentConverter.value = converterConfigs[type]
  fromUnit.value = currentConverter.value.units[0]
  toUnit.value = currentConverter.value.units[1]
  converterInput.value = ''
  converterOutput.value = ''
  showConverter.value = true
}

const onFromUnitChange = (e) => {
  fromUnit.value = currentConverter.value.units[e.detail.value]
  convert()
}

const onToUnitChange = (e) => {
  toUnit.value = currentConverter.value.units[e.detail.value]
  convert()
}

const convert = () => {
  if (!converterInput.value || !fromUnit.value || !toUnit.value) {
    converterOutput.value = ''
    return
  }

  const input = parseFloat(converterInput.value)
  if (isNaN(input)) {
    converterOutput.value = ''
    return
  }

  if (currentConverter.value.title === '温度转换') {
    converterOutput.value = convertTemperature(input, fromUnit.value, toUnit.value)
  } else {
    const fromFactor = currentConverter.value.conversions[fromUnit.value]
    const toFactor = currentConverter.value.conversions[toUnit.value]
    const result = (input * fromFactor) / toFactor
    converterOutput.value = result.toFixed(4)
  }
}

const convertTemperature = (value, from, to) => {
  let celsius
  switch (from) {
    case '摄氏度':
      celsius = value
      break
    case '华氏度':
      celsius = (value - 32) * 5/9
      break
    case '开尔文':
      celsius = value - 273.15
      break
  }

  switch (to) {
    case '摄氏度':
      return celsius.toFixed(2)
    case '华氏度':
      return (celsius * 9/5 + 32).toFixed(2)
    case '开尔文':
      return (celsius + 273.15).toFixed(2)
  }
}

const closeConverter = () => {
  showConverter.value = false
}

// 备忘录功能
const saveMemo = () => {
  if (!memoContent.value.trim()) {
    uni.showToast({ title: '请输入内容', icon: 'none' })
    return
  }

  const memo = {
    content: memoContent.value,
    time: new Date().toLocaleString()
  }
  memoList.value.unshift(memo)
  memoContent.value = ''
  
  uni.showToast({ title: '保存成功', icon: 'success' })
}

const loadMemo = (index) => {
  memoContent.value = memoList.value[index].content
}

const closeMemo = () => {
  showMemo.value = false
  memoContent.value = ''
}

// 二维码功能
const generateQRCode = () => {
  if (!qrcodeText.value.trim()) {
    uni.showToast({ title: '请输入内容', icon: 'none' })
    return
  }
  
  // 这里应该调用二维码生成API
  // 暂时使用模拟数据
  qrcodeImage.value = '/static/placeholder.png'
  uni.showToast({ title: '二维码生成成功', icon: 'success' })
}

const saveQRCode = () => {
  uni.saveImageToPhotosAlbum({
    filePath: qrcodeImage.value,
    success: () => {
      uni.showToast({ title: '保存成功', icon: 'success' })
    },
    fail: () => {
      uni.showToast({ title: '保存失败', icon: 'none' })
    }
  })
}

const closeQRCode = () => {
  showQRCode.value = false
  qrcodeText.value = ''
  qrcodeImage.value = ''
}

// 手电筒功能
const toggleFlashlight = () => {
  uni.showToast({ title: '手电筒功能开发中', icon: 'none' })
}

// 监听输入变化
const watchConverterInput = () => {
  convert()
}

// 生命周期
onMounted(() => {
  // 监听单位转换输入
  watchConverterInput()
})
</script>

<style scoped>
.container {
  background-color: #f5f5f5;
  min-height: 1200rpx;
  padding: 20rpx 20rpx 240rpx 20rpx;
}

.cancel-btn {
  font-size: 28rpx;
  color: #3D76FF;
  margin-left: 20rpx;
}

/* 工具容器 */
.tools-container {
  padding: 20rpx;
}

.tool-section {
  margin-bottom: 30rpx;
}

.section-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
  margin-bottom: 20rpx;
  display: block;
}

.tool-grid {
  display: flex;
  flex-wrap: wrap;
  gap: 20rpx;
}

.tool-item {
  width: calc(30% - 15rpx);
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20rpx 10rpx;
  background: #fff;
  border-radius: 16rpx;
  box-shadow: 0 2rpx 8rpx rgba(0, 0, 0, 0.1);
}

.tool-icon-wrapper {
  width: 90rpx;
  height: 90rpx;
  border-radius: 50%;
  display: flex;
  align-items: center;
  justify-content: center;
  margin-bottom: 12rpx;
}

.tool-icon {
  width: 50rpx;
  height: 50rpx;
}

.tool-label {
  font-size: 24rpx;
  color: #333;
  text-align: center;
}

/* 弹窗样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  z-index: 1000;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-content {
  width: 90%;
  max-height: 80%;
  background: #fff;
  border-radius: 16rpx;
  overflow: hidden;
}

.modal-header {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 30rpx;
  border-bottom: 1rpx solid #eee;
}

.modal-title {
  font-size: 32rpx;
  font-weight: bold;
  color: #333;
}

.close-btn {
  width: 60rpx;
  height: 60rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.close-icon {
  font-size: 40rpx;
  color: #999;
}

/* 计算器样式 */
.calculator-modal {
  width: 95%;
  max-width: 600rpx;
}

.calculator-display {
  padding: 30rpx;
  background: #f8f9fa;
  text-align: right;
}

.calculator-expression {
  font-size: 24rpx;
  color: #666;
  margin-bottom: 10rpx;
  display: block;
}

.calculator-result {
  font-size: 48rpx;
  font-weight: bold;
  color: #333;
  display: block;
}

.calculator-buttons {
  padding: 20rpx;
}

.button-row {
  display: flex;
  margin-bottom: 10rpx;
}

.calc-btn {
  flex: 1;
  height: 80rpx;
  margin: 0 5rpx;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 28rpx;
  font-weight: bold;
}

.btn-number {
  background: #fff;
  color: #333;
  border: 1rpx solid #ddd;
}

.btn-operator {
  background: #f8f9fa;
  color: #3D76FF;
  border: 1rpx solid #ddd;
}

.btn-clear {
  background: #ff6b6b;
  color: #fff;
  border: 1rpx solid #ff6b6b;
}

.btn-equal {
  background: #3D76FF;
  color: #fff;
  border: 1rpx solid #3D76FF;
}

.btn-zero {
  flex: 2;
}

/* 单位转换样式 */
.converter-modal {
  width: 90%;
  max-width: 500rpx;
}

.converter-content {
  padding: 30rpx;
}

.converter-input-group {
  display: flex;
  align-items: center;
  margin-bottom: 20rpx;
}

.converter-input {
  flex: 1;
  height: 80rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  margin-right: 20rpx;
}

.converter-picker {
  width: 200rpx;
  height: 80rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  display: flex;
  align-items: center;
  justify-content: center;
}

.picker-text {
  font-size: 28rpx;
  color: #333;
}

.converter-arrow {
  text-align: center;
  margin: 20rpx 0;
}

.arrow-icon {
  width: 40rpx;
  height: 40rpx;
}

/* 备忘录样式 */
.memo-modal {
  width: 90%;
  max-width: 600rpx;
}

.memo-content {
  padding: 30rpx;
}

.memo-textarea {
  width: 100%;
  height: 300rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  padding: 20rpx;
  font-size: 28rpx;
  background: #fff;
  resize: none;
}

.memo-count {
  text-align: right;
  font-size: 24rpx;
  color: #999;
  margin-top: 10rpx;
}

.memo-actions {
  display: flex;
  align-items: center;
}

.save-btn {
  font-size: 28rpx;
  color: #3D76FF;
  margin-right: 20rpx;
}

.memo-list {
  padding: 0 30rpx 30rpx;
  border-top: 1rpx solid #eee;
}

.memo-list-title {
  font-size: 28rpx;
  font-weight: bold;
  color: #333;
  margin: 20rpx 0;
  display: block;
}

.memo-item {
  background: #f8f9fa;
  border-radius: 8rpx;
  padding: 20rpx;
  margin-bottom: 15rpx;
}

.memo-item-content {
  font-size: 26rpx;
  color: #333;
  line-height: 1.5;
  margin-bottom: 10rpx;
  display: block;
}

.memo-item-time {
  font-size: 24rpx;
  color: #999;
}

/* 二维码样式 */
.qrcode-modal {
  width: 90%;
  max-width: 500rpx;
}

.qrcode-content {
  padding: 30rpx;
}

.qrcode-input {
  width: 100%;
  height: 80rpx;
  border: 2rpx solid #eee;
  border-radius: 8rpx;
  padding: 0 20rpx;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.generate-btn {
  width: 100%;
  height: 80rpx;
  background: #3D76FF;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  font-size: 28rpx;
  margin-bottom: 20rpx;
}

.qrcode-display {
  text-align: center;
}

.qrcode-image {
  width: 300rpx;
  height: 300rpx;
  margin-bottom: 20rpx;
}

.save-qrcode-btn {
  background: #4CAF50;
  color: #fff;
  border: none;
  border-radius: 8rpx;
  padding: 15rpx 30rpx;
  font-size: 26rpx;
}
</style>